//
//  CQPullDownToRefreshController.swift
//  weibo
//
//  Created by chengqiang on 16/7/27.
//  Copyright © 2016年 chengqiangBiaodashi. All rights reserved.
//

import UIKit


//下拉状态枚举
enum PullDownToRefreshControllerStatus {
    case Normal   //下拉刷新
    case Pulling  //释放刷新
    case Refreshing //正在刷新
}


//下拉刷新控件
class CQPullDownToRefreshController: UIView {

    private let PullDownToRefreshControllerHeight: CGFloat = 60
    //下拉刷新的闭包
    var refreshiongCallback:(()->Void)?
    
    private var currentStatus:PullDownToRefreshControllerStatus = .Normal{
        didSet{
            switch currentStatus {
            case .Normal:
                print("normal")
                
                messagelable.text="下拉刷新"
                UIView.animateWithDuration(0.25, animations: { ()->Void in
                    self.arrowImageView.transform = CGAffineTransformIdentity
                })
            case .Pulling:
                print("pulling")
              
                messagelable.text = "释放刷新"

                UIView.animateWithDuration(0.25, animations: { ()->Void in
                    self.arrowImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            case .Refreshing:
                print("refreshing")
                
                self.arrowImageView.hidden = true
                self.loadingImageView.hidden = false
                messagelable.text="正在刷新..."
                let animation = CABasicAnimation(keyPath: "transform.rotation")
                animation.toValue = 2*M_PI
                animation.duration = 0.75
                animation.repeatCount = MAXFLOAT
                animation.removedOnCompletion = false
                //添加到动画上面
                loadingImageView.layer.addAnimation(animation, forKey: "anim")
                UIView.animateWithDuration(0.25, animations: { ()->Void in
                    self.newSuperScrollew?.contentInset.top = self.newSuperScrollew!.contentInset.top + self.PullDownToRefreshControllerHeight

                    
                })
               //告诉别人刷新的状态
            self.refreshiongCallback?()
            }
        }
    }
    
    ///父控件
    var newSuperScrollew:UIScrollView?
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(frame: CGRect) {
        let neFrame = CGRect(x: 0, y: -PullDownToRefreshControllerHeight, width: UIScreen.mainScreen().bounds.size.width, height: 60)

        super.init(frame: neFrame)
        
        setupUI()
        
    }
    //MARK：－公开的方法
    
    //进入刷新
    func begainfreshing(){
        self.currentStatus = .Refreshing
    }
    //结束刷新
    func endfreshing()  {
        if self.currentStatus == .Refreshing{
            self.currentStatus = .Normal
            
            //结束转轮  箭头显示出来
            self.loadingImageView.layer.removeAllAnimations()
            self.loadingImageView.hidden = true
            self.arrowImageView.hidden = false
            
            
            UIView.animateWithDuration(0.25, animations: { ()->Void in
                self.newSuperScrollew?.contentInset.top = self.newSuperScrollew!.contentInset.top - self.PullDownToRefreshControllerHeight
                
            })
        }
    }
    //设置布局
    private func setupUI(){
        //默认隐藏转轮
        
        self.loadingImageView.hidden = true
        self.addSubview(loadingImageView)
        self.addSubview(arrowImageView)
        self.addSubview(messagelable)
        
        //关闭story关联来实现代码添加约束
        loadingImageView.translatesAutoresizingMaskIntoConstraints = false
        arrowImageView.translatesAutoresizingMaskIntoConstraints = false
        messagelable.translatesAutoresizingMaskIntoConstraints = false
        
        
        //箭头
        self.addConstraint(NSLayoutConstraint(item: arrowImageView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: -25))
        self.addConstraint(NSLayoutConstraint(item: arrowImageView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        //转轮
        self.addConstraint(NSLayoutConstraint(item: loadingImageView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: arrowImageView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        self.addConstraint(NSLayoutConstraint(item: loadingImageView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: arrowImageView, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        
        //文字
        self.addConstraint(NSLayoutConstraint(item: messagelable, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: arrowImageView, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 30))
        self.addConstraint(NSLayoutConstraint(item: messagelable, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
    }
    
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        if newSuperview is UIScrollView{
            self.newSuperScrollew = newSuperview as? UIScrollView
            
            self.newSuperScrollew?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions(rawValue:0), context: nil)
        }
    }
    //移除KVO
    deinit{
        self.newSuperScrollew?.removeObserver(self, forKeyPath: "contentOffset")
    }
    //实现KVO方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if self.newSuperScrollew!.dragging{
            if self.currentStatus == .Pulling && self.newSuperScrollew?.contentOffset.y > -124{
                self.currentStatus = .Normal
                
            }else if self.currentStatus == .Normal && self.newSuperScrollew?.contentOffset.y <= -124 {
                self.currentStatus = .Pulling
            }
            
        }else{
            if self.currentStatus == .Pulling{
                self.currentStatus = .Refreshing
            }
        }
    }
    
    
    //MARK:-懒加载控件
    //箭头
    private lazy var arrowImageView:UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //转轮
    private lazy var loadingImageView:UIImageView = UIImageView(image: UIImage(named: "tableview_loading"))
    //文字
    private lazy var messagelable:UILabel = {
       let lable = UILabel()
        lable.text="下拉刷新"
        lable.font=UIFont.systemFontOfSize(15)
        lable.textColor = UIColor.darkGrayColor()
        return lable
    }()
    
}
